package com.rhino.security.handler;
import com.alibaba.fastjson.JSON;
import com.rhino.security.constants.SecurityConstants;
import com.rhino.security.vo.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 身份校验失败处理器，如 token失效或者错误，直接返回前端认证失败信息。
 */
@Slf4j
@Component
public class EntryPointUnauthorizedHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.debug("校验token出错：", authException);
        Object expiredJwtException = request.getAttribute(SecurityConstants.EXPIRED_JWT_EXCEPTION);
        log.debug("JWT 异常信息：",JSON.toJSONString(expiredJwtException));
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(SecurityConstants.APPLICATION_JSON_UTF8_VALUE);

        RestResult restResult=RestResult.UNAUTH("身份认证失败，请重新登录！");
        PrintWriter writer = response.getWriter();
        if (expiredJwtException != null) {
            restResult.setMsg("用户无权限，请重新授权登录！");
        }
        writer.write(JSON.toJSONString(restResult));
        writer.close();
    }
}